# encoding:Utf8

import os
import sys
import shutil
import redis


class Pub2Redis:
    _path_proj = None

    @classmethod
    def run_luapack(cls):
        bin_l = "./lua" if sys.platform == "windows" else "lua"
        cmd_str = "{lbin} squish --no-minify".format(lbin=bin_l)
        os.system(cmd_str)

    @classmethod
    def pack_tar(cls, ptool):
        print("packing lua...")
        os.chdir(ptool)
        cls.run_luapack()
        os.chdir(cls._path_proj)
        rel_file = os.path.relpath("init.lua")
        if (not os.path.isfile(rel_file)):

            sys.exit()
        return rel_file

    @classmethod
    def upload_redis(cls, pfile, host, pwd):
        print("connect to redis <host=%s>..." % host)
        r = redis.Redis(host=host,
                        port=6379, db=14, password=pwd)
        r.publish("nodemcu_init", open(pfile).read())

    @classmethod
    def execute(cls, proj, host="pitoy.heyzf.com", pwd=None):
        cls._path_proj = proj
        TOOL_PATH = os.path.join(proj, "tools")

        f_lua = cls.pack_tar(TOOL_PATH)
        cls.upload_redis(f_lua, host, pwd)


if __name__ == "__main__":
    projpath = os.path.dirname(os.getcwd())
    Pub2Redis.execute(projpath)
